package day_2022_7_to_8.day48;

/**
 * @author haomin
 * @date 2022/08/31 18:06
 **/
public class Day46_8_Offer29_spiralOrder {
    class Solution {
        public int[] spiralOrder(int[][] matrix) {
            if(matrix.length == 0 || matrix[0].length == 0) return new int[0];
            int l = 0, r = matrix[0].length-1, u = 0, d = matrix.length-1, index = 0;
            int len = matrix.length * matrix[0].length;
            int[] res = new int[len];
            while(true){
                for(int i = l;i <= r;++i) {
                    res[index] = matrix[u][i]; index++;
                }
                if(++u > d) break;
                for(int i = u;i <= d;++i) {
                    res[index] = matrix[i][r]; index++;
                }
                if(--r < l) break;
                for(int i = r;i >= l; --i) {
                    res[index] = matrix[d][i]; index++;
                }
                if(--d < u) break;
                for(int i = d;i >= u;--i) {
                    res[index] = matrix[i][l]; index++;
                }
                if(++l > r) break;
            }
            return res;
        }
    }
}